package com.library.count.dao;

import com.framework.BaseDao;
import com.library.entity.Count;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Repository
public class CountDaoImpl extends BaseDao<Count,String> {

	/*根据参数查询oneCount*/
	public Count findCountByProperty(Map paramsMap){
		int i = 0;
		int j = 0;
		String key;
		StringBuilder hql = new StringBuilder("from Count c");
		List<Object> params = new ArrayList();

		if(paramsMap.size() != 0){
			Iterator<String> it = paramsMap.keySet().iterator();
			hql.append(" where ");
			while (it.hasNext()) {
				key = it.next();
				params.add(paramsMap.get(key));

				if(j != 0){
					if(params.get(i) != null)
						hql.append(" and c."+ key + "=?");
					else{
						hql.append(" and c."+ key + " is null");
						params.remove(i);
						++j;
						continue;
					}
				} else{
					if(params.get(i) != null)
						hql.append(" c."+ key + "=?");
					else{
						hql.append(" c."+ key + " is null");
						params.remove(i);
						++j;
						continue;
					}

				}
				++i;
				++j;
			}
		}
		try{
			return super.findOne(hql.toString(),params.toArray());
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	/*根据参数查询list*/
	public List<Count> findCountsByProperty(Map paramsMap){
		int i = 0;
		int j = 0;
		String key;
		StringBuilder hql = new StringBuilder("from Count c");
		List<Object> params = new ArrayList();

		if(paramsMap.size() != 0){
			Iterator<String> it = paramsMap.keySet().iterator();
			hql.append(" where ");
			while (it.hasNext()) {
				key = it.next();
				params.add(paramsMap.get(key));

				if(j != 0){
					if(params.get(i) != null)
						hql.append(" and c."+ key + "=?");
					else{
						hql.append(" and c."+ key + " is null");
						params.remove(i);
						++j;
						continue;
					}
				} else{
					if(params.get(i) != null)
						hql.append(" c."+ key + "=?");
					else{
						hql.append(" c."+ key + " is null");
						params.remove(i);
						++j;
						continue;
					}
				}
				++i;
				++j;
			}
		}
		try{
			return super.findByProperty(hql.toString(),params.toArray());
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	public Count findByDate(String date){
		try{
			return super.findOne("from Count c where c.date=?", new Object[]{date});
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	public void saveCount(Count count){
		try {
			this.save(count);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void updateCount(Count count){
		try {
			this.update(count);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void deleteCount(Count count){
		try {
			this.delete(count);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
